#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
充值管理API路由
"""

from flask import Blueprint, request, jsonify
from models.recharge import Recharge
from models.user import User
from database import db
from utils.decorators import admin_required, token_required
from datetime import datetime, timedelta
from sqlalchemy import or_
import jwt

recharge_bp = Blueprint('recharge', __name__)

@recharge_bp.route('/', methods=['GET'])
@admin_required
def get_recharges(admin):
    """获取充值记录列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        payment_status = request.args.get('payment_status', '')
        start_date = request.args.get('start_date', '')
        end_date = request.args.get('end_date', '')
        
        # 构建查询
        query = Recharge.query
        
        if search:
            query = query.join(User).filter(or_(
                Recharge.recharge_no.like(f'%{search}%'),
                User.nickname.like(f'%{search}%')
            ))
        
        if payment_status:
            query = query.filter(Recharge.payment_status == payment_status)
        
        if start_date:
            start = datetime.strptime(start_date, '%Y-%m-%d')
            query = query.filter(Recharge.created_at >= start)
        
        if end_date:
            end = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
            query = query.filter(Recharge.created_at < end)
        
        # 分页查询
        pagination = query.order_by(Recharge.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        recharges = pagination.items
        
        return jsonify({
            'success': True,
            'data': {
                'recharges': [recharge.to_dict() for recharge in recharges],
                'pagination': {
                    'page': page,
                    'pages': pagination.pages,
                    'per_page': per_page,
                    'total': pagination.total,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取充值记录失败: {str(e)}'}), 500

@recharge_bp.route('/statistics', methods=['GET'])
@admin_required  
def get_recharge_statistics(admin):
    """获取充值统计信息"""
    try:
        # 基础统计
        total_recharges = Recharge.query.count()
        paid_recharges = Recharge.query.filter(Recharge.payment_status == 'paid').count()
        
        # 总充值金额
        total_amount = db.session.query(db.func.sum(Recharge.total_amount)).filter(
            Recharge.payment_status == 'paid'
        ).scalar() or 0
        
        # 今日充值
        today = datetime.now().date()
        today_amount = db.session.query(db.func.sum(Recharge.total_amount)).filter(
            Recharge.created_at >= today,
            Recharge.created_at < today + timedelta(days=1),
            Recharge.payment_status == 'paid'
        ).scalar() or 0
        
        return jsonify({
            'success': True,
            'data': {
                'total_recharges': total_recharges,
                'paid_recharges': paid_recharges,
                'total_amount': float(total_amount),
                'today_amount': float(today_amount)
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取统计信息失败: {str(e)}'}), 500

@recharge_bp.route('/miniprogram', methods=['POST'])
@token_required
def miniprogram_recharge(user):
    """小程序充值接口"""
    try:
        data = request.get_json()
        package_type = data.get('package_type')
        amount = float(data.get('amount', 0))
        
        if not package_type or amount <= 0:
            return jsonify({'success': False, 'message': '参数错误'}), 400
        
        # 计算赠送金额
        bonus_amount = 0
        if package_type == '充值300元特惠套餐':
            bonus_amount = 50  # 300元送50元
        elif package_type == '充值500元限时套餐':
            bonus_amount = 100  # 500元送100元
        elif package_type == '充值1000元VIP套餐':
            bonus_amount = 300  # 1000元送300元
        
        total_amount = amount + bonus_amount
        
        # 创建充值记录
        recharge = Recharge(
            user_id=user.id,
            package_type=package_type,
            amount=amount,
            bonus_amount=bonus_amount,
            total_amount=total_amount,
            payment_method='wechat',
            payment_status='paid',  # 模拟支付成功
            paid_at=datetime.now()
        )
        
        # 更新用户余额
        user.balance += total_amount
        user.total_recharge += amount
        
        db.session.add(recharge)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '充值成功',
            'data': {
                'recharge': recharge.to_dict(),
                'new_balance': float(user.balance)
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'充值失败: {str(e)}'}), 500